package com.whut.monitor.service.impl;

import com.whut.monitor.dao.IHBaseDao;
import com.whut.monitor.dao.IHBaseRestDao;
import com.whut.monitor.service.IHbaseService;
import com.whut.monitor.util.HbaseUtil;
import com.whut.monitor.util.ProtocolUtil;
import com.whut.monitor.vo.DiagnosisSensorVo;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.math3.linear.Array2DRowRealMatrix;
import org.apache.commons.math3.stat.descriptive.moment.Mean;
import org.apache.commons.math3.stat.descriptive.moment.StandardDeviation;
import org.apache.commons.math3.stat.descriptive.rank.Max;
import org.apache.commons.math3.stat.descriptive.rank.Min;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.*;

import static com.whut.monitor.util.AlgorithmUtil.dataClean;
import static com.whut.monitor.util.DateUtil.getTimeList10s;
import static com.whut.monitor.util.FileUtil.save;
import static com.whut.monitor.util.FileUtil.saveCsv;
import static com.whut.monitor.util.HbaseUtil.*;
import static com.whut.monitor.util.MatUtil.combineRight;
import static com.whut.monitor.util.MatUtil.transpose;
import static com.whut.monitor.util.ProtocolUtil.*;
import static com.whut.monitor.util.SystemUtil.getMd5;
import static com.whut.monitor.util.WuzhongUtil.*;

/**
 * @author Sandeepin
 *         HBase服务层实现
 */
@Service
public class HbaseServiceImpl implements IHbaseService {
    private static final Logger logger = Logger.getLogger(HbaseServiceImpl.class);

    @Autowired
    private IHBaseRestDao hBaseDao;

    /**
     * 向Hbase中增加多条RowKey数据
     *
     * @param rowkeyAndValue 设计的RowKey、传感器数值数组(逗号间隔)
     * @return 布尔-成功与否
     */
    @Override
    public Boolean adds(Map<String, String> rowkeyAndValue) {
        // table表名，family列族，qua列。Hbase设计列族不能多
        String table = "wuzhong";
        String family = "d";
        String qua = "k";
        Boolean result = false;
        if (!ProtocolUtil.TestMode && rowkeyAndValue.size() > 0) {
            result = hBaseDao.adds(table, rowkeyAndValue, family, qua);
        }
        return result;
    }


    /**
     * 同步数据总集到HBase
     *
     * @param contentMap 输入map
     * @return 布尔
     */
    @Override
    public Boolean syncData(Map<String, String> contentMap) throws IOException {
        long startTime = System.currentTimeMillis();

        String table = "wuzhong";
        String family = "d";
        String qua = "k";
        boolean result = false;
        if (!ProtocolUtil.TestMode && contentMap.size() > 0) {
            result = hBaseDao.adds(table, contentMap, family, qua);
        }

        String costTime = (System.currentTimeMillis() - startTime) / 1000.0 + "s";
        System.out.println("[poi]hbaseSyncData:" + costTime);
        return result;
    }


    /**
     * 输入 日期 和 id数组, 查询 对应传感器值
     *
     * @param date    日期
     * @param idArray ID数组
     * @param map     查询结果 RowKey+Value
     * @return 结果数组
     */
    @Override
    public String[][] finds(String date, String idArray, Map<String, String> map) {
        // 【预整理要查询的RowKey】
        // 前台收到的数据（日期+传感器编号） 转 HbaseRowKey记录Map
        Map<String, String> hbaseRowkeyMap = webData2HbaseRowkey(date, idArray);
        // 设备编号 例：01
        String devNumEn = hbaseRowkeyMap.get("devNumEn");
        // 传感器类型 例：DT
        String sensorType = hbaseRowkeyMap.get("sensorType");
        // 日期  例：171020
        String dateInRowkey = hbaseRowkeyMap.get("Date");
        if (dateInRowkey.isEmpty()) {
            dateInRowkey = "000000";
        }

        // 【查Hbase表】
        // table表名，指定start和end的RowKey(批量查询，Rowkey字典排序)
        String table = "wuzhong";
        String start = devNumEn + sensorType + dateInRowkey + "000000";
        String end = devNumEn + sensorType + dateInRowkey + "235959";
        // 存放 RowKey + value 的Map
        Map<String, String> rowkeyAndValueMap = new TreeMap<>();
        hBaseDao.finds(table, start, end, rowkeyAndValueMap);

        // RowKey中提取Time作为新key
        // map中key为标准时间time, value为Hbase中的value
        for (String akey : rowkeyAndValueMap.keySet()) {
            // 例：hbaseTime = 171020
            String hbaseTime = akey.substring(4, 16).trim();
            // 例：time = 12:13 只显示时和分
            String time = hbaseTime2StandardTime(hbaseTime);
            map.put(time, rowkeyAndValueMap.get(akey));
        }

        // 由Hbase解析出对应传感器值-带波长修复
//        long startTime1 = System.currentTimeMillis();
        String[][] outArray = hbaseValue2OneValue(map, idArray, sensorType);
//        logger.info("[poi]SFTtoFix:" + (System.currentTimeMillis() - startTime1) + "ms =" + (System.currentTimeMillis() - startTime1) / 1000 + "s");

        // 如果是波长，则转温度
        String waveType = "SFT";
        long startTime2 = System.currentTimeMillis();
        String[] tempidArray = idArray.split(",", -1);
        String strSFT = tempidArray[0].substring(4, 7).trim();
        if (strSFT.equals(waveType)) {
            for (int i = 0; i < outArray.length; ++i) {
                for (int j = 0; j < outArray[i].length; ++j) {
                    outArray[i][j] = ProtocolUtil.waveToTemp(tempidArray[i], outArray[i][j]);
                    // 异常值归零
                    if (Double.parseDouble(outArray[i][j]) < 0 || Double.parseDouble(outArray[i][j]) > 100) {
                        outArray[i][j] = "00.0";
                    }
                }
            }
        }
        logger.info("[poi]SFTtoWave:" + (System.currentTimeMillis() - startTime2) + "ms =" + (System.currentTimeMillis() - startTime2) / 1000 + "s");

        return outArray;
    }

    /**
     * 输入 日期、设备号、传感器类型, 查询Hbase中传感器当天的数据-杨赟
     *
     * @param date       日期
     * @param devNumEn   设备号
     * @param sensorType 传感器类型
     * @return 布尔
     */
    @Override
    public boolean searchs(String date, String devNumEn, String sensorType, Map<String, String> map) {
        String[] ymd = date.split("-");
        if (ymd.length != 3) {
            return false;
        }
        String Date = ymd[0].substring(2, 4) + ymd[1] + ymd[2];
        String table = "whutmonitor";            // Hbase表名-不变
        String start = devNumEn.substring(1, 3) + sensorType + Date + "000000";
        String end = devNumEn.substring(1, 3) + sensorType + Date + "235959";
        Map<String, String> map1 = new TreeMap<>();
        boolean b = hBaseDao.finds(table, start, end, map1);
        for (String aKey : map1.keySet()) {
            String HbaseTime = aKey.substring(4, 16).trim();
            String time = hbaseTime2StandardTime(HbaseTime);
            map.put(time, map1.get(aKey));
        }
        return b;
    }

    /**
     * 从Hbase获取传感器统计信息并初略诊断
     *
     * @param date          日期
     * @param sensorIDArray 传感器ID
     * @return 诊断结果数据类
     */
    @Override
    public List<DiagnosisSensorVo> findStatiData(String date, String sensorIDArray) {
        Map<String, String> map = new TreeMap<>();
        // 【预整理要查询的RowKey】
        // 前台收到的数据（日期+传感器编号） 转 HbaseRowKey记录Map
        Map<String, String> hbaseRowkeyMap = webData2HbaseRowkey(date, sensorIDArray);
        // 设备编号 例：01
        String devNumEn = hbaseRowkeyMap.get("devNumEn");
        // 传感器类型 例：DT
        String sensorType = hbaseRowkeyMap.get("sensorType");
        // 日期  例：171020
        String dateInRowkey = hbaseRowkeyMap.get("Date");
        if (dateInRowkey.isEmpty()) {
            dateInRowkey = "000000";
        }

        // 【查Hbase表】
        // table表名，指定start和end的RowKey(批量查询，Rowkey字典排序)
        String table = "wuzhong";
        String start = devNumEn + sensorType + dateInRowkey + "000000";
        String end = devNumEn + sensorType + dateInRowkey + "235959";
        // 存放 RowKey + value 的Map
        Map<String, String> rowkeyAndValueMap = new TreeMap<>();
        hBaseDao.finds(table, start, end, rowkeyAndValueMap);

        // RowKey中提取Time作为新key
        // map中key为标准时间time, value为Hbase中的value
        for (String akey : rowkeyAndValueMap.keySet()) {
            // 例：hbaseTime = 171020
            String hbaseTime = akey.substring(4, 16).trim();
            // 例：time = 12:13 只显示时和分
            String time = hbaseTime2StandardTime(hbaseTime);
            map.put(time, rowkeyAndValueMap.get(akey));
        }

        // 将时间(key) 数据集合(value)放入数组中, 之后方便调用数学库
        int mapRow = map.size();
        int mapCol = 0;
        // value存valueArr
        int i = 0;
        for (String akey : map.keySet()) {
            if (i == 0) {
                String[] valueArr = map.get(akey).split(",");
                mapCol = valueArr.length;
            }
            i++;
        }
        // key存MapValue
        double[][] mapValue = new double[mapRow][mapCol];
        i = 0;
        for (String akey : map.keySet()) {
            String[] valueArr = map.get(akey).split(",");
            for (int j = 0; j < mapCol; j++) {
                mapValue[i][j] = Double.parseDouble(valueArr[j]);
                ;
            }
            i++;
        }
        // 至此得到了MapKey和MapValue

        // 输出数据(传感器编号 数据总数 最大值 最小值 平均值 标准差 诊断)
        String sensor = sensorIDArray.substring(4, 7).trim();
        String[] idArray = HbaseUtil.sensorIndex(sensor);
        int[] countArray = new int[mapRow];
        double[] maxArray = new double[mapRow];
        double[] minArray = new double[mapRow];
        double[] meanArray = new double[mapRow];
        double[] standeviaArray = new double[mapRow];
        String[] diagnosisArray = new String[mapRow];
        // 数据用Mat类处理
        Array2DRowRealMatrix mat = new Array2DRowRealMatrix(mapValue);
        Max max = new Max();
        Min min = new Min();
        // 算术平均值
        Mean mean = new Mean();
        // 标准差
        StandardDeviation standardDeviation = new StandardDeviation();
        // 输出list
        List<DiagnosisSensorVo> ul = new ArrayList<>();
        for (int j = 0; j < mat.getColumnDimension(); j++) {
            countArray[j] = mat.getColumnVector(j).getDimension();
            maxArray[j] = max.evaluate(mat.getColumnVector(j).toArray());
            minArray[j] = min.evaluate(mat.getColumnVector(j).toArray());
            meanArray[j] = mean.evaluate(mat.getColumnVector(j).toArray());
            standeviaArray[j] = standardDeviation.evaluate(mat.getColumnVector(j).toArray());

            if ("SDT".equals(sensor) || "SFT".equals(sensor)) {
                // 诊断规则: 温度数据平均值在1-36内正常, -5-1 36-50内疑似正常
                if (meanArray[j] >= 1 && meanArray[j] <= 36) {
                    diagnosisArray[j] = "正常";
                } else if (meanArray[j] <= -5 || meanArray[j] >= 50) {
                    diagnosisArray[j] = "故障";
                } else {
                    diagnosisArray[j] = "疑似故障";
                }
            }
            if ("SST".equals(sensor)) {
                // 诊断规则: 未定
                if (standeviaArray[j] >= 50) {
                    diagnosisArray[j] = "故障";
                } else {
                    diagnosisArray[j] = "正常";
                }
            }
            if ("SCD".equals(sensor)) {
                // 诊断规则: ccd平均值在-0.05--0.05内正常, -0.1-0.1内疑似正常
                if (meanArray[j] >= -0.05 && meanArray[j] <= 0.05) {
                    diagnosisArray[j] = "正常";
                } else if (meanArray[j] <= -0.1 || meanArray[j] >= 0.1) {
                    diagnosisArray[j] = "故障";
                } else {
                    diagnosisArray[j] = "疑似故障";
                }
            }
            // 写入DiagnosisSensorVo list
            // 取三位小数(.33显示0.330)
            DecimalFormat decimalFormat = new DecimalFormat("0.000");
            DiagnosisSensorVo u = new DiagnosisSensorVo();
            assert idArray != null;
            u.setSensorID(idArray[j]);
            u.setCount(String.valueOf(countArray[j]));
            u.setMaxValue(decimalFormat.format(maxArray[j]));
            u.setMinValue(decimalFormat.format(minArray[j]));
            u.setMeanValue(decimalFormat.format(meanArray[j]));
            u.setSd(decimalFormat.format(standeviaArray[j]));
            u.setDiagnosis(diagnosisArray[j]);
            ul.add(u);
        }

//		for(int j=0; j< Mat.getColumnDimension(); j++)
//		{
//			System.out.println("maxArray[j]: "+maxArray[j]);
//			System.out.println("minArray[j]: "+minArray[j]);
//			System.out.println("meanArray[j]: "+meanArray[j]);
//			System.out.println("standeviaArray[j]: "+standeviaArray[j]);
//			System.out.println("diagnosisArray[j]: "+diagnosisArray[j]);
//			System.out.println();
//		}
        return ul;
    }

    /**
     * 合并从HBase中取的数据到csv中-只取数据有的交集（没做后续适配，会越界）
     *
     * @param startTime 开始时间，例171108120000
     * @param endTime   结束时间，例171108140000
     * @param idArray   需要合并的传感器编号
     * @return 文件保存位置
     */
    @Override
    public String combineToCsv(String startTime, String endTime, String[] idArray) throws IOException {
        // 从idArray中提取CD、DT、ET、ST、FT、CN传感器类别，提取dev编号01
        String[] sensorArray = new String[idArray.length];
        String dev = "01";
        for (int i = 0; i < idArray.length; i++) {
            if (idArray[i].length() > 7) {
                dev = idArray[i].substring(1, 3);
                sensorArray[i] = idArray[i].substring(5, 7);
                // SCN去掉以统一idArray
                if ("CN".equals(sensorArray[i])) {
                    idArray[i] = idArray[i].replace("-SCN", "");
                }
            }
        }

        // 取数据放到outArrayList，包含用户要的数据
        String table = "wuzhong";
        List<String[][]> outArrayList = new ArrayList<>();
        List<String> formatTime = new ArrayList<>();
        boolean timeAlreadyHandle = false;
        for (int i = 0; i < sensorArray.length; i++) {
            String start = dev + sensorArray[i] + startTime;
            String end = dev + sensorArray[i] + endTime;
            Map<String, String> rowkeyAndValueMap = new TreeMap<>();
            hBaseDao.finds(table, start, end, rowkeyAndValueMap);
            // 滤除nan->0、inf>99，保障导出数据高度可用性
            // 顺便处理时间
            for (String aKey : rowkeyAndValueMap.keySet()) {
                // 滤除
                String value = rowkeyAndValueMap.get(aKey);
                value = value.replace("nan", "0");
                value = value.replace("inf", "99");
                rowkeyAndValueMap.put(aKey, value);
                // 处理时间
                if (!timeAlreadyHandle) {
                    String hbaseTime = aKey.substring(4, 16).trim();
                    if (hbaseTime.substring(10, 12).compareTo("30") >= 0) {
                        hbaseTime = hbaseTime.substring(0, 10) + "30";
                    } else {
                        hbaseTime = hbaseTime.substring(0, 10) + "00";
                    }
                    formatTime.add(hbaseTime2StandardTime(hbaseTime, "yyyy-MM-dd-HH:mm:ss"));
                }
            }
            timeAlreadyHandle = true;
            // Hbase数据转Array
            String[][] outArray = hbaseValue2OneValue(rowkeyAndValueMap, idArray[i], sensorArray[i]);
            // 矩阵转置成数据面向列来合表
            outArray = transpose(outArray);
            // 只有有数据的array才保存，没有要去掉idAarray中的对应项目
            if (outArray.length > 0) {
                outArrayList.add(outArray);
            }
            if (outArray.length <= 0) {
                // 三个#占位
                idArray[i] = "###";
            }
        }

        // 保存得到的数组
        String[][] time = new String[formatTime.size()][1];
        for (int i = 0; i < formatTime.size(); i++) {
            time[i][0] = formatTime.get(i);
        }
        String saveFileName = startTime + "~" + endTime + "_" + "Data.csv";
        String title = StringUtils.join(idArray, ",");
        title = "Time," + title + "\n";
        title = title.replace("###,", "");
        title = title.replace(",###", "");
        if (outArrayList.size() < 2) {
            // 单独一种数据不需要数据数组合并
            String[][] combineMat = combineRight(time, outArrayList.get(0));
            saveCsv(fileSavePath + saveFileName, title, combineMat);
        } else {
            // 2种以上数据需要合并
            String[][] combineMat = combineRight(outArrayList.get(0), outArrayList.get(1));
            for (int i = 2; i < outArrayList.size(); i++) {
                combineMat = combineRight(combineMat, outArrayList.get(i));
            }
            combineMat = combineRight(time, combineMat);
            saveCsv(fileSavePath + saveFileName, title, combineMat);
        }
        return fileSavePathWeb + saveFileName;
    }


    /**
     * 合并从HBase中取的数据到csv中-按用户设定的时间段严格生成，没有的补0
     *
     * @param startTime 开始时间，例171108120000
     * @param endTime   结束时间，例171108140000
     * @param idArray   需要合并的传感器编号
     * @return 文件保存位置
     * @throws IOException    io异常
     * @throws ParseException 表达式格式化异常
     */
    @Override
    public String combineToCsvAddZero(String startTime, String endTime, String[] idArray) throws IOException, ParseException, NoSuchAlgorithmException {

        // 设定创建的文件名，如果有，则直接下载文件
        String title = StringUtils.join(idArray, ",");
        title = "Time," + title + "\n";
        String fileFingerprint = getMd5(title + startTime + endTime);
        fileFingerprint = fileFingerprint.substring(0, 8);
        String saveFileName = startTime + "~" + endTime + "_" + "Data_" + fileFingerprint + ".csv";
        File file = new File(fileSavePath + saveFileName);
        if (file.exists()) {
            System.out.println("csv文件已经存在：" + saveFileName);
            return fileSavePathWeb + saveFileName;
        }

        System.out.println("开始生成csv文件：" + saveFileName);
        // TODO 越界问题比较复杂，只解决部分天数数据越界
        // 生成所有时间字符串, 10秒一次抽样导出
        String[] timeAll = getTimeList10s(startTime, endTime);

        // 从idArray中提取CD、DT、ET、ST、FT、CN传感器类别，提取dev编号01
        String[] sensorArray = new String[idArray.length];
        String dev = "01";
        for (int i = 0; i < idArray.length; i++) {
            if (idArray[i].length() > 7) {
                dev = idArray[i].substring(1, 3);
                // 得到sensorArray
                sensorArray[i] = idArray[i].substring(5, 7);
                // idArray修正 - SCN去掉以统一
                if ("CN".equals(sensorArray[i])) {
                    idArray[i] = idArray[i].replace("-SCN", "");
                }
            }
        }

        // 取数据放到outMapList，包含用户要的数据
        String table = "wuzhong";
        List<Map<String, String>> outMapList = new ArrayList<>();
        List<String[][]> outArrayList = new ArrayList<>();
        for (int i = 0; i < sensorArray.length; i++) {
            // Hbase取数据
            String start = dev + sensorArray[i] + startTime;
            String end = dev + sensorArray[i] + endTime;
            Map<String, String> rowkeyAndValueMap = new TreeMap<>();
            hBaseDao.finds(table, start, end, rowkeyAndValueMap);
            // 处理时间、滤除nan->0、inf>99，保障导出数据高度可用性
            Map<String, String> timeAndValueMap = new TreeMap<>();
            for (String aTimeAll : timeAll) {
                // 空缺值填0，等待后续覆盖
                timeAndValueMap.put(aTimeAll, sensorZeroValue(sensorArray[i]));
            }
            for (String aKey : rowkeyAndValueMap.keySet()) {
                // 滤除nan、inf
                String value = rowkeyAndValueMap.get(aKey);
                value = value.replace("nan", "0");
                value = value.replace("inf", "0");
                // 处理时间 30s以上的归30,30s一下的归0
//                if (aKey.length()<15){
//                    continue;
//                }
                String hbaseTime = aKey.substring(4, 16).trim();
//                hbaseTime = hbaseTime.substring(0, 10) + "00";
//                String formatTime = hbaseTime2StandardTime(hbaseTime, "yyyy-MM-dd-HH:mm:ss");
//                timeAndValueMap.put(formatTime, value);
                //【分两种情况】
//                // 对于2017-09-15之前的数据，秒舍去，写6次
                if (hbaseTime.compareTo("170915000000") < 0) {
                    hbaseTime = hbaseTime.substring(0, 10) + "00";
                    String formatTime = hbaseTime2StandardTime(hbaseTime, "yyyy-MM-dd-HH:mm:");
                    timeAndValueMap.put(formatTime + "00", value);
                    timeAndValueMap.put(formatTime + "10", value);
                    timeAndValueMap.put(formatTime + "20", value);
                    timeAndValueMap.put(formatTime + "30", value);
                    timeAndValueMap.put(formatTime + "40", value);
                    timeAndValueMap.put(formatTime + "50", value);
                }
//                // 对于2017-09-15之后的数据，采用10秒抽样一次导出，最后个位秒舍去
                if (hbaseTime.compareTo("170915000000") >= 0) {
                    hbaseTime = hbaseTime.substring(0, 11) + "0";
                    String formatTime = hbaseTime2StandardTime(hbaseTime, "yyyy-MM-dd-HH:mm:ss");
                    timeAndValueMap.put(formatTime, value);
                }
            }
            String[][] outArray = hbaseValue2OneValue(timeAndValueMap, idArray[i], sensorArray[i]);
            outArray = transpose(outArray);
            // 数据跳变修复
            dataClean(outArray);
            outArrayList.add(outArray);
        }

        // 保存得到的数组
        String[][] time = new String[timeAll.length][1];
        for (int i = 0; i < timeAll.length; i++) {
            time[i][0] = timeAll[i];
        }
        if (outArrayList.size() < 2) {
            // 单独一种数据不需要数据数组合并
            String[][] combineMat = combineRight(time, outArrayList.get(0));
            saveCsv(fileSavePath + saveFileName, title, combineMat);
        } else {
            // 2种以上数据需要合并
            String[][] combineMat = combineRight(outArrayList.get(0), outArrayList.get(1));
            for (int i = 2; i < outArrayList.size(); i++) {
                combineMat = combineRight(combineMat, outArrayList.get(i));
            }
            combineMat = combineRight(time, combineMat);
            saveCsv(fileSavePath + saveFileName, title, combineMat);
        }
        return fileSavePathWeb + saveFileName;
    }

    /**
     * 环境温度、电类传感器、FBG诊断
     *
     * @param date 日期
     * @return 诊断结果
     */
    @Override
    public Map<String, String> diagnosisSensor(String date) {
        List<String> time = new ArrayList<>();
        List<String> titleENV = new ArrayList<>();
        List<String> titleDSB = new ArrayList<>();
        List<String> titleFBG = new ArrayList<>();
        List<String> titleCCD = new ArrayList<>();
        double[][] env = getHbaseAllENV(date, titleENV, time, hBaseDao);
        double[][] dsb = getHbaseAllDSB(date, titleDSB, time, hBaseDao);
        double[][] fbg = getHbaseAllFBG(date, titleFBG, time, hBaseDao);
        double[][] ccd = getHbaseAllCCD(date, titleCCD, time, hBaseDao);

        Map<String, String> diagnosisResultENV = new TreeMap<>();
        Map<String, String> diagnosisResultDSB = new TreeMap<>();
        Map<String, String> diagnosisResultFBG = new TreeMap<>();
        Map<String, String> diagnosisResultCCD = new TreeMap<>();
        diagnosisENV(env, titleENV, diagnosisResultENV);
        diagnosisDSB(dsb, titleDSB, diagnosisResultDSB);
        diagnosisFBG(fbg, titleFBG, diagnosisResultFBG);
        diagnosisCCD(ccd, titleCCD, diagnosisResultCCD);

//        save(fileSavePath + "diagnosis_ENV_" + date + ".log", diagnosisResultENV);
//        save(fileSavePath + "diagnosis_DSB_" + date + ".log", diagnosisResultDSB);
//        save(fileSavePath + "diagnosis_FBG_" + date + ".log", diagnosisResultFBG);
//        save(fileSavePath + "diagnosis_CCD_" + date + ".log", diagnosisResultCCD);

        Map<String, String> diagnosisResultAll = new TreeMap<>();
        diagnosisResultAll.putAll(diagnosisResultENV);
        diagnosisResultAll.putAll(diagnosisResultDSB);
        diagnosisResultAll.putAll(diagnosisResultFBG);
        diagnosisResultAll.putAll(diagnosisResultCCD);
        return diagnosisResultAll;
    }

    @Override
    public String diagnosisSensorCacheFind(String date) {
        String table = "wuzhong";
        String rowKey = "diagnosisSensor" + date;
        String family = "d";
        String qualifier = "k";
        String value = hBaseDao.find(table, rowKey, family, qualifier);
        return value;
    }

    @Override
    public boolean diagnosisSensorCacheAdd(String rowKey, String value) {
        String table = "wuzhong";
        String family = "d";
        String qua = "k";
        return hBaseDao.add(table, rowKey, family, qua, value);
    }

    @Override
    public String test(String arg1) {
//        String date = arg1;
//        List<String> title1 = new ArrayList<>();
//        List<String> title2 = new ArrayList<>();
//        List<String> title3 = new ArrayList<>();
//        List<String> title4 = new ArrayList<>();
//        List<String> title5 = new ArrayList<>();
//        List<String> title6 = new ArrayList<>();
//        List<String> title7 = new ArrayList<>();
//        List<String> time = new ArrayList<>();
//        double[][] dsb  = getHbaseAllDSB(date, title1, time, hBaseDao);
//        double[][] fbgs = getHbaseAllFBGS(date, title2, time, hBaseDao);
//        double[][] fbgt = getHbaseAllFBGT(date, title3, time, hBaseDao);
//        double[][] fbg = getHbaseAllFBG(date, title4, time, hBaseDao);
//        double[][] env  = getHbaseAllENV(date, title5, time, hBaseDao);
//        double[][] ccd  = getHbaseAllCCD(date, title6, time, hBaseDao);
//        String[][]  cnc  = getHbaseAllCNC(date, title7, time, hBaseDao);

//        Map<String, String> diagnosisResultDSB = new TreeMap<>();
//        Map<String, String> diagnosisResultFBG = new TreeMap<>();
//        Map<String, String> diagnosisResultENV = new TreeMap<>();
//        diagnosisDSB(dsb, title1, diagnosisResultDSB);
//        diagnosisFBG(fbg, title4, diagnosisResultFBG);
//        diagnosisENV(env, title5, diagnosisResultENV);

//        save(fileSavePath + date+ "diagnosisResultDSB.log", diagnosisResultDSB);
//        save(fileSavePath + "diagnosisResultFBG_" + date + ".log", diagnosisResultFBG);
//        save(fileSavePath + date+ "diagnosisResultENV.log", diagnosisResultENV);


//        save(fileSavePath + date+ "0dsb.csv",dsb);
//        save(fileSavePath + date+ "1fbgs.csv",fbgs );
//        save(fileSavePath + date+ "2fbgt.csv",fbgt );
//        save(fileSavePath + date+ "3fbg.csv",fbg  );
//        save(fileSavePath + date+ "4env.csv",env  );
//        save(fileSavePath + date+ "5ccd.csv",ccd  );
//        if (cnc!=null){
//            save(fileSavePath + date+  "6cnc.csv",cnc  );
//        }
//        save(fileSavePath + "title1.txt",title1);
//        save(fileSavePath + "title2.txt",title2);
//        save(fileSavePath + "title3.txt",title3);
//        save(fileSavePath + "title4.txt",title4);
//        save(fileSavePath + "title5.txt",title5);
//        save(fileSavePath + "title6.txt",title6);
//        save(fileSavePath + "title7.txt",title7);
        return "OK";
    }
}
